﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.LowPriceHouse.Controllers
{
    [Description("房主")]
    public class OwnerController : BaseController
    {
        public IOwnerContract OwnerContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        #region 列表
        [Description("房主-列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId; 
            var query = from o in OwnerContract.Entities.Where(m => !m.IsDeleted)
                        select new
                        {
                            Id = o.Id,
                            Name = o.Name,
                            Phone = o.Phone,
                            Remark = o.Remark,
                            AgentID = o.AgentID,
                            StaffID = (from s in StaffContract.Entities where s.IsDeleted == false && o.StaffID == s.Id select s.Name).FirstOrDefault()
                        };
            if (search != "")
            {
                query = query.Where(m => m.Name.Contains(search));
            }
            if (agentid != 0)
            {
                query = query.Where(m => m.AgentID == agentid);
            }

            var total = query.Count();
            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion
        #region 添加
        [Description("房主-添加")]
        public ActionResult Insert()
        {
            intorcount();
            return View();
        }
        [HttpPost]
        public ActionResult InsertAsync(Owner entity)
        { 
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult(); 
            try
            {
                var count = OwnerContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        #region 修改
        [Description("房主-修改")]
        public ActionResult Edit(int id)
        {
            var entity = OwnerContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity; 
            intorcount();
            return View();
        }
        [HttpPost]
        public ActionResult EditAsync(Owner entity)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult(); 
            try
            {
                var count = OwnerContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        #region 房主删除
        [Description("房主-删除")]
        [HttpPost]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                OwnerContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Owner { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        #region 下拉框传值

        public void intorcount()
        { 
            List<SelectListItem> gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            var data = from sff in StaffContract.TrackEntities
                       select new SelectListItem
                       {
                           Value = sff.Id + "",
                           Text = sff.Name
                       };
            gridData.AddRange(data);
            ViewData["business"] = new SelectList(gridData); 
        }
        #endregion
    }
}